/**   
 * @Title: RechargeYinLian.java 
 * @Package com.esun.elk.ui.views.userinfo.recharge 
 * @Description: 手机银联支付
 * @author Kael gaojian@500wan.com
 * @date 2012-5-30 上午10:33:27   
 * Copyright (C) 2011 Shenzhen E-sun Sky Net Technology Co.,ltd.
 */
package com.esun.rabbit2.viewer.mainact.mylotteryact.recharg;

import java.io.StringReader;
import java.util.Hashtable;

import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.esun.config.Config;
import com.esun.config.Key;
import com.esun.config.Language;
import com.esun.model.UserInfo;
import com.esun.rabbit2.communicaters.recharg.YinLianCommunicater;
import com.esun.ui.R;
import com.esun.util.ViewerUtil;
import com.esun.util.log.EDebug;

/**
 * @ClassName: RechargeYinLian
 * @Description: 手机银联支付
 * @author: Kael gaojian@500wan.com
 * @date: 2012-5-30 上午10:33:27
 * 
 */
public class RechargeYinLian extends Activity implements android.view.View.OnClickListener {
	// 输入金额的EditText
	private EditText recharge_yinlian_edt_num;
	// 提交
	private Button recharge_yinlian_btn_submit;
	// 返回
	private ImageButton recharge_yinlian_btn_goBack;
	// 手机银联支付通信接口
	YinLianCommunicater yinlianCommunicater;
	// 用户名
	private String username;
	// 用户密码
	private String userpassword;
	// 客户端版本
	private String version;
	// 充值金额
	private String recharge_num;
	private Handler handler;
	// 进度条
	private ProgressDialog yinLianProgressDialog;
	// 银联充值通信成功
	private final int YINLIAN_SUCCEED = 1;
	// 银联充值通信失败
	private final int YINLIAN_FAIL = 2;
	// 网络不可用
	private final int CONNECT_FAIL = 3;
	// 插件支付页面
	public final static String CMD_PAY_PLUGIN = "cmd_pay_plugin";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.recharge_yinlian_act);
		init();
		initHandler();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.recharge_yinlian_btn_submit:
			// 获取充值金额
			recharge_num = recharge_yinlian_edt_num.getText().toString();
			// 判断充值金额是否为空
			if (recharge_num == null || recharge_num.equals(Config.NULLMARK)) {
				// ViewerUtil.showTipDialog(RechargeYinLian.this, Language.MSG_CHONGZHI_JINE, false);
				Toast.makeText(RechargeYinLian.this, Language.MSG_CHONGZHI_JINE, Toast.LENGTH_SHORT).show();
			} else {
				try {
					Integer.parseInt(recharge_num);
					yinLianProgressDialog.show();
					yinLianThread();
				} catch (Exception e) {
					Toast.makeText(RechargeYinLian.this, Language.MSG_RECHARGE_MONEY_LIMIT, Toast.LENGTH_SHORT).show();
				}
			}
			break;
		case R.id.recharge_yinlian_btn_goBack:
			// 后退
			RechargeYinLian.this.finish();
			break;
		default:
			break;
		}

	}

	/**
	 * @Title: init
	 * @Description: 初始化
	 * @param: 设定文件
	 * @return: void 返回类型
	 * @throws
	 */
	private void init() {
		yinLianProgressDialog = ViewerUtil.showProgressDialog(RechargeYinLian.this, Language.TIP_TRANSACTION_INIT);
		recharge_yinlian_edt_num = (EditText) findViewById(R.id.recharge_yinlian_edt_num);
		recharge_yinlian_edt_num.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
		recharge_yinlian_btn_submit = (Button) findViewById(R.id.recharge_yinlian_btn_submit);
		recharge_yinlian_btn_goBack = (ImageButton) findViewById(R.id.recharge_yinlian_btn_goBack);
		recharge_yinlian_btn_submit.setOnClickListener(this);
		recharge_yinlian_btn_goBack.setOnClickListener(this);
		username = UserInfo.getUserInfo().getUserName();
		userpassword = UserInfo.getUserInfo().getUserPwd();
		version = UserInfo.getUserInfo().getCurrentVersion();
	}

	/**
	 * @Title: yinLianThread
	 * @Description: 银联充值通信线程
	 * @param: 设定文件
	 * @return: void 返回类型
	 * @throws
	 */
	private void yinLianThread() {
		new Thread() {

			@Override
			public void run() {
				super.run();
				if (yinlianCommunicater == null) {
					yinlianCommunicater = new YinLianCommunicater();
				}
				try {
					boolean b = yinlianCommunicater.succeed(username, userpassword, recharge_num, version);
					// 通信成功，订单初始化成功
					if (b) {
						Message msg = handler.obtainMessage(YINLIAN_SUCCEED);
						handler.sendMessage(msg);
					} else {// 通信成功，订单初始化失败
						Message msg = handler.obtainMessage(YINLIAN_FAIL);
						handler.sendMessage(msg);
					}
				} catch (Exception e) {// 通信失败
					Message msg = handler.obtainMessage(CONNECT_FAIL);
					handler.sendMessage(msg);
					e.printStackTrace();
				}
			}

		}.start();
	}

	/**
	 * @Title: initHandler
	 * @Description: 初始化handler
	 * @param: 设定文件
	 * @return: void 返回类型
	 * @throws
	 */
	private void initHandler() {
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				yinLianProgressDialog.dismiss();
				switch (msg.what) {
				case YINLIAN_SUCCEED:
					Hashtable<String, String> hashtable = new Hashtable<String, String>();
					hashtable = yinlianCommunicater.getYinLianInfo();
					String manchertId = hashtable.get(Key.KEY_MERCHANTID);
					String merchantOrderId = hashtable.get(Key.KEY_MERCHANTORDERID);
					String application = hashtable.get(Key.KEY_APPLICATION);
					String version = hashtable.get(Key.KEY_VERSION);
					String merchantOrderTime = hashtable.get(Key.KEY_MERCHANTORDERTIME);
					String backEndUrl = hashtable.get(Key.KEY_BACKENDURL);
					String sign = hashtable.get(Key.KEY_SIGN);
					String xml = LanchPay(manchertId, merchantOrderId, application, version, merchantOrderTime, sign, backEndUrl);
					ComponentName com = new ComponentName("com.esun.ui", "com.unionpay.upomp.lthj.plugin.ui.MainActivity");
					Intent intent = new Intent();
					intent.setComponent(com);
					intent.putExtra("action_cmd", CMD_PAY_PLUGIN);
					Bundle bundle = new Bundle();
					EDebug.o(this, xml);
					bundle.putByteArray("xml", xml.getBytes());
					bundle.putString("merchantPackageName", "com.intent.action.PAYBACK");
					intent.putExtras(bundle);
					startActivity(intent);
					break;
				case YINLIAN_FAIL:
					String failMsg = yinlianCommunicater.getServerMsg();
					ViewerUtil.showTipDialog(RechargeYinLian.this, failMsg, false);
					break;
				case CONNECT_FAIL:
				  
				  
				  Toast.makeText(RechargeYinLian.this, Language.STR_CONNECTIONFAIL.toString(), Toast.LENGTH_SHORT).show();
					//ViewerUtil.showTipDialog(RechargeYinLian.this, Language.STR_CONNECTIONFAIL, false);
				default:
					break;
				}
			}

		};
	}

	/**
	 * @Title: LanchPay
	 * @Description: 组织启动插件的xml
	 * @param: @param manchertId
	 * @param: @param merchantOrderId
	 * @param: @param application
	 * @param: @param version
	 * @param: @param merchantOrderTime
	 * @param: @param sign
	 * @param: @param url
	 * @param: @return 设定文件
	 * @return: String 返回类型
	 * @throws
	 */
	public String LanchPay(String manchertId, String merchantOrderId, String application, String version, String merchantOrderTime, String sign, String url) {

		String lanchpay = "<?xml version=" + "'1.0' " + "encoding=" + "'UTF-8' " + "?>" + "<upomp  application='" + application + "' version='" + version + "' >" + "<merchantId>" + manchertId
				+ "</merchantId>"

				+ "<merchantOrderId>" + merchantOrderId + "</merchantOrderId>"

				+ "<merchantOrderTime>" + merchantOrderTime + "</merchantOrderTime>"

				+ "<backEndUrl>" + url + "</backEndUrl>"

				+ "<sign>" + sign + "</sign>" + "</upomp>";

		return lanchpay;

	}

	// 回调客户端 获取
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		EDebug.o("RechargeYinLain--->onNewIntent");
		Bundle bundle = intent.getExtras();
		if (bundle != null) {
			byte[] xml = bundle.getByteArray("xml");
			if (xml != null) {
				String strxml = new String(xml);
				EDebug.o("RechargeYinLain--->xml" + strxml);
				if (strxml == null || strxml.equals(Config.NULLMARK)) {
					Toast.makeText(RechargeYinLian.this, Language.MSG_TRANSACTION_FAILS, Toast.LENGTH_SHORT).show();
				} else {
					xmlReader(strxml);
					Toast.makeText(RechargeYinLian.this, Language.MSG_TRANSACTION_RESULT + tableResult.get("respDesc") + Config.LEFT_ROUND_BR + tableResult.get("respCode") + Config.RIGHT_ROUND_BR,
							Toast.LENGTH_SHORT).show();
				}
			}
		} else {
			EDebug.o("RechargeYinLain--->传回空");
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		EDebug.o(RechargeYinLian.this, "onResume()");
	}

	private Hashtable<String, String> tableResult = new Hashtable<String, String>();

	private void xmlReader(String strXML) {
		// 对获取的xml字段转化为输入源
		StringReader readStrXml = new StringReader(strXML);
		InputSource source = new InputSource(readStrXml);

		try {
			// 使用SAX和DefaltHandler工具解析xml字段
			ReceiveHandler xmlToolHandler = new ReceiveHandler();
			SAXParserFactory saxFactory = SAXParserFactory.newInstance();

			XMLReader xmlReader = saxFactory.newSAXParser().getXMLReader();
			xmlReader.setContentHandler(xmlToolHandler);
			xmlReader.parse(source);
			EDebug.o(this, Config.OPTIONIS_END);

		} catch (Exception e) {
			EDebug.o(RechargeYinLian.this, e.toString());
			EDebug.o(this, Config.OPTIONIS_END);
		}
	}

	class ReceiveHandler extends DefaultHandler {

		private boolean is_root = false;
		private String tagName;

		@Override
		public void startDocument() throws SAXException {
			// TODO Auto-generated method stub
			super.startDocument();
		}

		@Override
		public void endDocument() throws SAXException {
			// TODO Auto-generated method stub
			super.endDocument();
		}

		// 判定是否为根节点root,如果是,解析开始
		@Override
		public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
			if (localName.equals("info")) {
				EDebug.o(this, Config.CRYSTRING + localName);
				this.is_root = true;
			}
			this.tagName = localName;

		}

		// 判定根节点是否结束
		@Override
		public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
			if (localName.equals("info")) {
				this.is_root = false;
			}
		}

		// 在hashtable中写入子节点数据
		@Override
		public void characters(char ch[], int start, int length) {
			if (this.is_root) {
				String strValue = new String(ch, start, length);

				// 诡异的判断...存在回车和空格的情况下子节点会出现3次
				if (strValue.indexOf(" ") != 0 && strValue.indexOf("\n") != 0 && strValue.indexOf("\t") != 0) {
					tableResult.put(this.tagName, strValue);
				}
			}
		}

	}

}
